<template>
  <div>
    <input type="text" @click="openByDrop($event)" v-model="display">
    <div class="calendar-dropdown" :style="{'left':left+'px','top':top+'px'}" v-if="show">
        <calendar :range="range" @select="select"></calendar>
    </div>
  </div>
</template>
<script>
import calendar from './calendar.vue';

export default{
  components:{
    calendar
  },
  props:{
    range:{type:Boolean,default:false}
  },
  data:function(){
    return {
      left:0,top:0,show:false,display:''
    }
  },
  methods:{
    select(a,b){
      this.show=false;
      if (this.range){
        this.display=a.join('-')+' ~ '+b.join('-');
        b=this.arr2str(b);
      }else this.display=a.join('-');
      a=this.arr2str(a);
      this.$emit('select',a,b);
    },
    arr2str(arr){
      if (arr[1]<10) arr[1]='0'+arr[1];
      if (arr[2]<10) arr[2]='0'+arr[2];
      return `${arr[0]}-${arr[1]}-${arr[2]}`;
    },
    openByDrop(e){
        this.show=true;
        this.left=e.target.offsetLeft+19;
        this.top=e.target.offsetTop+70;
        
        e.stopPropagation();
        window.setTimeout(()=>{
            document.addEventListener("click",(e)=>{
                this.show=false;
                document.removeEventListener("click",()=>{},false);
            },false);
        },1000)
    },
  }
}
</script>
<style scoped>
input{
  box-sizing: border-box;
  border-radius: 2px;
  border:1px solid #dedede;
  padding:10px;
  background:url() no-repeat 8px 10px;
  padding-left: 36px;
  color:#666;
}
.calendar-dropdown{
    background: #fff;
    position: absolute;
    left:0;
    top:0;
    padding:20px;
    border: 1px solid #eee;
    border-radius: 2px;
}
.calendar-dropdown:before {
    position: absolute;
    left:30px;
    top: -10px;
    content: "";
    border:5px solid rgba(0, 0, 0, 0);
    border-bottom-color: #DEDEDE;
}
.calendar-dropdown:after {
    position: absolute;
    left:30px;
    top: -9px;
    content: "";
    border:5px solid rgba(0, 0, 0, 0);
    border-bottom-color: #fff;
}
</style>